package com.mc.common.utils;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * hesison的序列化与反序列化
 */
public class HessianUtil {
	/**
	 * 对象进行序列化
	 * @param obj
	 * @param <T>
	 * @return
	 * @throws IOException
	 */
	public static <T> byte[] serialize(T obj) throws IOException {
		if (obj == null){
			throw new NullPointerException();
		}
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		HessianOutput ho = new HessianOutput(os);
		ho.writeObject(obj);
		return os.toByteArray();
	}

	/**
	 * 数据进行反序列化
	 * @param by
	 * @param <T>
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public static <T> T deserialize(byte[] by) throws IOException {
		if (by == null)
			throw new NullPointerException();
		ByteArrayInputStream is = new ByteArrayInputStream(by);
		HessianInput hi = new HessianInput(is);
		return (T) hi.readObject();
	}
}
